{% extends "base.html" %}

{% set current_menu = 'work_hour' %}
{% set current_page = 'work_hour_deviation' %}

{% block title %}工时偏差分析{% endblock %}

{% block content %}
<div class="container mx-auto">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('work_hour.stats') }}" class="text-gray-500 hover:text-gray-700">工时统计</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">工时偏差分析</li>
        </ol>
    </nav>

    <!-- 筛选区域 -->
    <div class="bg-white rounded-lg shadow-md p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label for="project-filter" class="block text-sm font-medium text-gray-700 mb-1">项目</label>
                <select id="project-filter" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                    <option value="">所有项目</option>
                    {% for project in projects %}
                    <option value="{{ project.id }}">{{ project.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label for="user-filter" class="block text-sm font-medium text-gray-700 mb-1">负责人</label>
                <select id="user-filter" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                    <option value="">所有人员</option>
                    {% for user in users %}
                    <option value="{{ user.id }}">{{ user.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label for="date-range-filter" class="block text-sm font-medium text-gray-700 mb-1">时间范围</label>
                <select id="date-range-filter" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                    <option value="7">最近7天</option>
                    <option value="30" selected>最近30天</option>
                    <option value="90">最近90天</option>
                    <option value="custom">自定义</option>
                </select>
            </div>
            <div class="flex items-end">
                <button id="filter-btn" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                    <i class="fas fa-filter mr-2"></i>筛选
                </button>
            </div>
        </div>
    </div>

    <!-- 偏差概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-md p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-600">
                    <i class="fas fa-tasks text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">任务总数</p>
                    <p class="text-2xl font-semibold text-gray-900">{{ deviation_stats.total_tasks or 0 }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow-md p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-600">
                    <i class="fas fa-check-circle text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">正常任务</p>
                    <p class="text-2xl font-semibold text-gray-900">{{ deviation_stats.normal_tasks or 0 }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow-md p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-600">
                    <i class="fas fa-exclamation-triangle text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">偏差任务</p>
                    <p class="text-2xl font-semibold text-gray-900">{{ deviation_stats.deviation_tasks or 0 }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow-md p-4">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-red-100 text-red-600">
                    <i class="fas fa-clock text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">平均偏差率</p>
                    <p class="text-2xl font-semibold text-gray-900">{{ "%.1f"|format(deviation_stats.avg_deviation_rate or 0) }}%</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 偏差分析图表 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-md p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">任务工时偏差分布</h3>
            <div id="deviation-chart" style="height: 300px;"></div>
        </div>
        <div class="bg-white rounded-lg shadow-md p-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">偏差原因分析</h3>
            <div id="deviation-reason-chart" style="height: 300px;"></div>
        </div>
    </div>

    <!-- 偏差任务列表 -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">偏差任务列表</h3>
                <div class="flex space-x-2">
                    <button class="text-sm bg-blue-600 text-white py-1 px-3 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                        <i class="fas fa-download mr-1"></i>导出
                    </button>
                </div>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务名称</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">项目</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">负责人</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划工时</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实际工时</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">偏差率</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">偏差原因</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for task in deviation_tasks %}
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ task.name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">{{ task.project_name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">{{ task.assignee_name }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ task.estimated_hours or 0 }}h</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ task.actual_hours or 0 }}h</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            {% set deviation_rate = task.deviation_rate or 0 %}
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                {% if deviation_rate > 20 %}
                                    bg-red-100 text-red-800
                                {% elif deviation_rate > 10 %}
                                    bg-yellow-100 text-yellow-800
                                {% else %}
                                    bg-green-100 text-green-800
                                {% endif %}">
                                {{ "%.1f"|format(deviation_rate) }}%
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ task.deviation_reason or '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button class="text-blue-600 hover:text-blue-900 mr-3" onclick="showDeviationDetail({{ task.id }})">
                                <i class="fas fa-eye"></i> 查看
                            </button>
                            <button class="text-indigo-600 hover:text-indigo-900" onclick="editDeviationReason({{ task.id }})">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="8" class="px-6 py-4 text-center text-sm text-gray-500">
                            暂无偏差任务数据
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 偏差详情模态框 -->
<div id="deviation-detail-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900">偏差详情</h3>
                <button onclick="closeDeviationDetail()" class="text-gray-400 hover:text-gray-500">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="deviation-detail-content" class="mt-2 px-2 py-3">
                <!-- 详情内容将通过JavaScript动态填充 -->
            </div>
            <div class="items-center px-4 py-3">
                <button onclick="closeDeviationDetail()" class="px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md w-full shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300">
                    关闭
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 偏差原因编辑模态框 -->
<div id="deviation-reason-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-1/2 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900">编辑偏差原因</h3>
                <button onclick="closeDeviationReason()" class="text-gray-400 hover:text-gray-500">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="deviation-reason-form" class="mt-2 px-2 py-3">
                <input type="hidden" id="deviation-task-id" name="task_id">
                <div class="mb-4">
                    <label for="deviation-reason" class="block text-sm font-medium text-gray-700">偏差原因</label>
                    <textarea id="deviation-reason" name="deviation_reason" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"></textarea>
                </div>
                <div class="mb-4">
                    <label for="deviation-solution" class="block text-sm font-medium text-gray-700">解决方案</label>
                    <textarea id="deviation-solution" name="deviation-solution" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"></textarea>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeDeviationReason()" class="px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300">
                        取消
                    </button>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white text-base font-medium rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
{{ super() }}
<script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
<script>
     // 初始化图表
     function initCharts() {
         // 初始化偏差分布图表
         const deviationChart = echarts.init(document.getElementById('deviation-chart'));
         const deviationOption = {
             tooltip: {
                 trigger: 'axis',
                 axisPointer: {
                     type: 'shadow'
                 }
             },
             legend: {
                 data: ['预估工时', '实际工时']
             },
             grid: {
                 left: '3%',
                 right: '4%',
                 bottom: '3%',
                 containLabel: true
             },
             xAxis: {
                 type: 'category',
                 data: {{ deviation_chart_data.categories|tojson }}
             },
             yAxis: {
                 type: 'value',
                 name: '任务数量'
             },
             series: [
                 {
                     name: '预估工时',
                     type: 'bar',
                     data: {{ deviation_chart_data.estimated_hours|tojson }},
                     itemStyle: {
                         color: '#3B82F6'
                     }
                 },
                 {
                     name: '实际工时',
                     type: 'bar',
                     data: {{ deviation_chart_data.actual_hours|tojson }},
                     itemStyle: {
                         color: '#10B981'
                     }
                 }
             ]
         };
         deviationChart.setOption(deviationOption);

         // 初始化偏差原因图表
         const deviationReasonChart = echarts.init(document.getElementById('deviation-reason-chart'));
         const deviationReasonOption = {
             tooltip: {
                 trigger: 'item',
                 formatter: '{a} <br/>{b}: {c} ({d}%)'
             },
             legend: {
                 orient: 'vertical',
                 left: 10,
                 data: {{ deviation_reason_chart_data.categories|tojson }}
             },
             series: [
                 {
                     name: '偏差原因',
                     type: 'pie',
                     radius: ['50%', '70%'],
                     avoidLabelOverlap: false,
                     itemStyle: {
                         borderRadius: 10,
                         borderColor: '#fff',
                         borderWidth: 2
                     },
                     label: {
                         show: false,
                         position: 'center'
                     },
                     emphasis: {
                         label: {
                             show: true,
                             fontSize: 16,
                             fontWeight: 'bold'
                         }
                     },
                     labelLine: {
                         show: false
                     },
                     data: {{ deviation_reason_chart_data.data|tojson }}
                 }
             ]
         };
         deviationReasonChart.setOption(deviationReasonOption);

         // 响应窗口大小变化
         window.addEventListener('resize', function() {
             deviationChart.resize();
             deviationReasonChart.resize();
         });
     }

     // 页面加载完成后初始化图表
     window.addEventListener('load', initCharts);

    // 显示偏差详情
    function showDeviationDetail(taskId) {
        fetch(`/api/task/deviation/detail/${taskId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const content = document.getElementById('deviation-detail-content');
                    content.innerHTML = `
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <p class="text-sm font-medium text-gray-500">任务名称</p>
                                <p class="text-sm text-gray-900">${data.task.name}</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">项目</p>
                                <p class="text-sm text-gray-900">${data.task.project_name}</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">负责人</p>
                                <p class="text-sm text-gray-900">${data.task.assignee_name}</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">状态</p>
                                <p class="text-sm text-gray-900">${data.task.status}</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">计划工时</p>
                                <p class="text-sm text-gray-900">${data.task.estimated_hours}h</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">实际工时</p>
                                <p class="text-sm text-gray-900">${data.task.actual_hours}h</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">偏差率</p>
                                <p class="text-sm text-gray-900">${data.task.deviation_rate}%</p>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-500">偏差日期</p>
                                <p class="text-sm text-gray-900">${data.task.deviation_date}</p>
                            </div>
                            <div class="col-span-2">
                                <p class="text-sm font-medium text-gray-500">偏差原因</p>
                                <p class="text-sm text-gray-900">${data.task.deviation_reason || '-'}</p>
                            </div>
                            <div class="col-span-2">
                                <p class="text-sm font-medium text-gray-500">解决方案</p>
                                <p class="text-sm text-gray-900">${data.task.deviation_solution || '-'}</p>
                            </div>
                        </div>
                    `;
                    document.getElementById('deviation-detail-modal').classList.remove('hidden');
                } else {
                    showFlashMessage('获取偏差详情失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showFlashMessage('获取偏差详情失败，请稍后重试', 'error');
            });
    }

    // 关闭偏差详情
    function closeDeviationDetail() {
        document.getElementById('deviation-detail-modal').classList.add('hidden');
    }

    // 编辑偏差原因
    function editDeviationReason(taskId) {
        document.getElementById('deviation-task-id').value = taskId;
        document.getElementById('deviation-reason').value = '';
        document.getElementById('deviation-solution').value = '';
        
        // 获取当前偏差原因和解决方案
        fetch(`/api/task/deviation/detail/${taskId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('deviation-reason').value = data.task.deviation_reason || '';
                    document.getElementById('deviation-solution').value = data.task.deviation_solution || '';
                    document.getElementById('deviation-reason-modal').classList.remove('hidden');
                } else {
                    showFlashMessage('获取偏差详情失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showFlashMessage('获取偏差详情失败，请稍后重试', 'error');
            });
    }

    // 关闭偏差原因编辑
    function closeDeviationReason() {
        document.getElementById('deviation-reason-modal').classList.add('hidden');
    }

    // 提交偏差原因表单
    document.getElementById('deviation-reason-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const taskId = document.getElementById('deviation-task-id').value;
        const deviationReason = document.getElementById('deviation-reason').value;
        const deviationSolution = document.getElementById('deviation-solution').value;
        
        fetch(`/api/task/deviation/update/${taskId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                deviation_reason: deviationReason,
                deviation_solution: deviationSolution
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showFlashMessage('偏差原因更新成功', 'success');
                closeDeviationReason();
                location.reload(); // 刷新页面以显示更新后的数据
            } else {
                showFlashMessage('更新失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showFlashMessage('更新失败，请稍后重试', 'error');
        });
    });

    // 筛选按钮点击事件
    document.getElementById('filter-btn').addEventListener('click', function() {
        const projectId = document.getElementById('project-filter').value;
        const userId = document.getElementById('user-filter').value;
        const dateRange = document.getElementById('date-range-filter').value;
        
        // 构建URL参数
        const params = new URLSearchParams();
        if (projectId) params.append('project_id', projectId);
        if (userId) params.append('user_id', userId);
        if (dateRange) params.append('date_range', dateRange);
        
        // 重定向到筛选后的页面
        window.location.href = '{{ url_for("work_hour.work_hour_deviation") }}?' + params.toString();
    });
</script>
{% endblock %}